package com.order.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.goods.entity.Order;
import com.goods.enumeration.CodeEnumeration;
import com.goods.utils.Result;
import com.goods.utils.ResultUtils;
import com.order.fegin.StockService;
import com.order.service.OrderService;
import com.order.utils.LockUtils;
import flow.OrderFlow;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/order")
@Slf4j
@Api(tags = "订单管理")
public class OrderController {
    private String  lockey="";
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Autowired(required = false)
    private StockService stockService;

    @Autowired
    private LockUtils lockUtils;

    @Autowired
    private OrderService orderService;
       @PostConstruct
      public void init(){
           redisTemplate.opsForValue().set("shopid","tesst");
      }

    @SentinelResource(
            value = "flow",
            blockHandlerClass= OrderFlow.class,
            blockHandler = "blockHandler"
            )
    @GetMapping("/saveOrder")
    @ApiOperation("新增订单")
    @GlobalTransactional
    public Result saveOrder(){
        ///huangfeissss
        boolean lock = lockUtils.tryLock(  "stock", TimeUnit.SECONDS,10, 10);
        try{
            if(lock){
                Result stock = stockService.reduceStock(1);
                Order order=new Order(2,"开心果","12",1,1);
                if (!stock.getCode().equals(200)) {
                    return ResultUtils.error(CodeEnumeration.ADD_FAIL.getCode(),CodeEnumeration.ADD_FAIL.getMessage());
                }
                orderService.saveOrder(order);
            }

        }

        finally {
            lockUtils.unlock("stock");
        }


        return ResultUtils.ok();
    }





}
